package com.h3c.nem.aspect;

import com.h3c.nem.annotation.CheckRole;
import com.h3c.nem.enums.RoleType;
import com.h3c.nem.service.CommService;
import com.h3c.nem.utils.AppBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Component
@Slf4j
@Aspect
public class CheckRoleAop {

    @Resource
    CommService commService;

    @Pointcut("@annotation(com.h3c.nem.annotation.CheckRole)")
    public void pointCut() {}

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        // 从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取切入点所在的方法
        Method method = signature.getMethod();
        // 获取方法内返回值
        CheckRole checkRole = method.getAnnotation(CheckRole.class);
        RoleType[] roleTypes = checkRole.roleArray();

        int hitCount = 0;
        String userRole = commService.getLoginUserRole();
        if (StringUtils.hasText(userRole)) {
            for (String role : userRole.split(",")) {
                for (RoleType type : roleTypes) {
                    if (StringUtils.hasText(role) && role.equals(type.getCode())) {
                        hitCount++;
                    }
                }
            }
            if (hitCount == 0) {
                throw new AppBusinessException("暂无权限访问");
            }
        } else {
            throw new AppBusinessException("暂无权限访问");
        }
    }
}
